package com.powernode.util;

import com.powernode.domain.MinioItem;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName MinioUtil
 * @Description minio工具类
 * @Date 2024/07/28 16:57
 */
@Component
@Slf4j
public class MinIoUtils {

    @Resource
    private MinioClient minioClient;
    @Value("${minio.endpoint}")
    private String url;

    /**
     * 查看存储bucket是否存在
     * @param bucketName 存储bucket
     * @return boolean
     */
    public Boolean bucketExists(String bucketName) {
        Boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return found;
    }

    /**
     * 创建存储bucket
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 文件上传
     * @param file 文件
     * @param bucketName 存储bucket
     * @return 文件名
     */
    public String upload(MultipartFile file, String bucketName) {
        String reNameFileName = null;
        try {
            reNameFileName =
                    Objects.requireNonNull(file.getOriginalFilename())
                            .substring(0,file.getOriginalFilename().lastIndexOf("."))
                            + System.currentTimeMillis()
                            + file.getOriginalFilename()
                            .substring(file.getOriginalFilename().lastIndexOf("."));
            PutObjectArgs objectArgs = PutObjectArgs
                    .builder()
                    .bucket(bucketName)
                    .object(reNameFileName)
                    .stream(file.getInputStream(),file.getSize(),-1)
                    .contentType(file.getContentType())
                    .build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return url + "/" + bucketName + "/" + reNameFileName;
    }

    /**
     * 文件下载
     * @param bucketName 存储bucket名称
     * @param fileName 文件名称
     * @param res response
     * @return Boolean
     */
    public boolean download(String bucketName, String fileName, HttpServletResponse res) {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucketName)
                .object(fileName).build();
        try (GetObjectResponse response = minioClient.getObject(objectArgs)){
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
                while ((len=response.read(buf))!=-1){
                    os.write(buf,0,len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
                //设置强制下载不打开
                res.setContentType("application/force-download");
                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()){
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 查看文件对象
     * @param bucketName 存储bucket名称
     * @return 存储bucket内文件对象信息
     */
    public List<MinioItem> listObjects(String bucketName) {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(bucketName).build());
        List<MinioItem> minioItems = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                Item item = result.get();
                MinioItem minioItem = new MinioItem();
                minioItem.setFileName(item.objectName());
                minioItem.setFileSize(item.size());
                minioItems.add(minioItem);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return minioItems;
    }

    /**
     * 根据文件路径得到预览文件绝对地址
     *
     * @param bucketName  桶名
     * @param fileName    文件路径
     * @return url
     */
    public String getPreviewFileUrl(String bucketName, String fileName) {
        try {
            Map<String, String> reqParams = new HashMap<String, String>(1);
            reqParams.put("response-content-type", "application/json");
            return minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(bucketName)
                            .object(fileName)
                            .expiry(7, TimeUnit.DAYS)
                            .extraQueryParams(reqParams)
                            .build());
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 批量删除文件对象
     * @param bucketName 存储bucket名称
     * @param objects 对象名称集合
     */
    public Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objects) {
        List<DeleteObject> dos = objects.stream()
                .map(e -> new DeleteObject(e))
                .collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(
                RemoveObjectsArgs
                        .builder()
                        .bucket(bucketName)
                        .objects(dos)
                        .build());
        return results;
    }

    /**
     * 删除文件
     * @param bucketName 存储bucket名称
     * @param fileName 文件名称
     * @return 结果
     */
    public int removeFile(String bucketName,String fileName){
        try {
            //判断桶是否存在
            boolean res=minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (res) {
                //删除文件
                minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName)
                        .object(fileName).build());
            }
        } catch (Exception e) {
            log.info("删除文件失败,文件名--" + fileName);
            e.printStackTrace();
            return 0;
        }
        return 1;
    }
}
